<?php
namespace app\api\controller;
use think\Exception;
use think\Request;
use app\base\model\Task;
use app\base\model\TaskLog;
use app\base\model\TaskImg;
use think\Config;
use think\Log;
use think\Cache;
class Index extends BaseC
{
    protected $taskModel;
    protected $task_log;
    protected $task_img;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        Config::load(APP_PATH.'api/config/config.php');
        $this->taskModel=new Task();
        $this->task_log =new TaskLog();
        $this->task_img =new TaskImg();
    }
    //登录接口
    public function wxMiniLogin(){
        $code=$this->request->param('code');
        $config=Config::get('wemini');
        Vendor('zoujingli.wechat-developer.include');
        $wxlogin = new \WeMini\Crypt($config);
        $reqData = $wxlogin->session($code);
        if(!isset($reqData['openid']) || !isset($reqData['session_key'])){
           $msg['message']=checkMsg(GET_DATA_FAILE);
           return $msg;
        }
        $count=$this->userModel->where(['openid'=>$reqData['openid']])->count();
        if($count<1){
            $is_first_login=1;
        }else{
            $is_first_login=0;
        }
        $msg['message']=checkMsg(GET_DATA_SUCCESS);
        $msg['openid']=$reqData['openid'];
        $msg['is_first_login']=$is_first_login;
        return $msg;
    }
    /**
     *登录
     * return json
     */
    public function login(){
        $user_name = $this->request->post('user_name');
        $phone     = $this->request->post('phone');
        $openid    = $this->request->post('openid');
        $invited_id= $this->request->post('invited_id',0);
        if($openid==''){
            $msg['message']=checkMsg(CANSHU_ERROR);
            return $msg;
        }
        $userInfo=$this->userModel->where(['openid'=>$openid])->find();
        if(empty($userInfo)){
             $insert_data=[
                 'user_name' =>$user_name,
                 'phone'     =>$phone,
                 'openid'    =>$openid,
                 'invited_id'=>$invited_id,
                 'integral'  =>0,
                 'add_time'  =>time()
             ];
             $insert_id=$this->userModel->insertGetId($insert_data);
             if($insert_id){
                 $session_id=GetRandStr(50);
                 $insert_data['uid']=$insert_id;
                // Session::set($session_id,$insert_data,'api');
                 Cache::set($session_id,$insert_data);
                 $msg=checkMsg(LOGIN_SUCCESS);
                 return ['message'=>$msg,'session_id'=>$session_id];
             }else{
                 $msg['message']=checkMsg(LOGIN_ERROR);
                 return $msg;
             }
        }else{
            $session_id=GetRandStr(50);
            Cache::set($session_id,$userInfo);
            $msg=checkMsg(LOGIN_SUCCESS);
            return ['message'=>$msg,'session_id'=>$session_id];
        }
    }
    /**
     *任务列表
     * return json
     */
   public function index(){
       if(empty($this->userInfo)){
           Log::info($this->userInfo);
           $msg['message']=checkMsg(LOGIN_ERROR);
           return $msg;
       }
        $pageNo = $this->request->post('pageNo',1);
        $pageSize = $this->request->post('pageSize',15);
        $task_list = $this->taskModel->where('views_num','>',0)->where('status','=',1)->order('type','asc')->order('add_time','asc')->field('tid,uid,title,total_num,views_num,action,add_time')->page($pageNo,$pageSize)->select();
        foreach($task_list as $key=>$value){
              $log_info=$this->task_log->where(['tid'=>$value['tid'],'uid'=>$this->user_id])->find();
              if(empty($log_info)){
                  $task_list[$key]['status']='';
              }else{
                  $time=time()-$log_info['addtime'];
                  if($log_info['status']==0){
                      if($time>300) {
                          $this->taskModel->where(['tid' => $value['tid']])->setInc('views_num', 1);
                          $this->task_log->where(['tid' => $value['tid'], 'uid' => $this->user_id])->delete();
                          $task_list[$key]['status'] = '';
                      }else{
                          $task_list[$key]['status'] = 0;
                      }
                  }elseif($log_info['status']==1){
                      $time=time()-$log_info['addtime'];
                      if($time>3600){
                          $this->task_log->startTrans();
                          try{
                              $this->task_log->save(['status'=>2],['tid'=>$value['tid'],'uid'=>$this->user_id]);
                              $taskInfo = $this->taskModel->where(['tid'=>$log_info['tid']])->find();
                              $action_arr=explode(',',$taskInfo['action']);
                              $num=count($action_arr);
                              $this->userModel->where(['uid'=>$log_info['uid']])->setInc('integral',$num);
                              $task_list[$key]['status']=2;
                              $this->task_log->commit();
                          }catch (Exception $e){
                              $this->task_log->rollback();
                              return $e->getMessage();
                          }
                      }else{
                          $task_list[$key]['status']=1;
                      }
                  }elseif($log_info['status']==3){
                       $task_list[$key]['reason']=$log_info['reason'];
                      $task_list[$key]['status']=$log_info['status'];
                  }else{
                      $task_list[$key]['status']=$log_info['status'];
                  }
              }
              if($value['uid']==$this->user_id){
                 $task_list[$key]['is_self']=1;
              }else{
                  $task_list[$key]['is_self']=0;
              }
              $time=(time()-$value['add_time']);
              if($time>=172800){
                   unset($task_list[$key]);
                   $task_info = $this->taskModel->where(['tid'=>$value['tid']])->find();
                   $action_arr=explode(',',$task_info['action']);
                   $int=(count($action_arr)*$task_info['views_num']);
                   $user_info=$this->userModel->where(['uid'=>$task_info['uid']])->find();
                   $user_int=$user_info['integral']+$int;
                   $this->userModel->save(['integral'=>$user_int],['uid'=>$task_info['uid']]);
                   $this->taskModel->where(['tid'=>$value['tid']])->delete();
              }
        }
       if(!empty($task_list)){
           $msg['message']=checkMsg(GET_DATA_SUCCESS);
           $msg['data']=$task_list;
       }else{
          $msg['message']=checkMsg(GET_DATA_FAILE);
          $msg['data']=[];
       }
       return $msg;
   }
   /**
    *发布任务
    *return json
    */
   public function pushTask(){
       if(empty($this->userInfo)){
         $msg['message']=checkMsg(LOGIN_ERROR);
         return $msg;
       }
       $title = $this->request->post('title');
       $link  = $this->request->post('link');
       $total_num=$this->request->post('total_num',1);
       $action   =$this->request->post('action');
       if(empty($title) || empty($link) || empty($action)){
           $msg['message']=checkMsg(CANSHU_ERROR);
           return $msg;
       }
       $action_arr=explode(',',$action);
       $total_inte=(count($action_arr)*$total_num);
       $userInfo = $this->userModel->where(['uid'=>$this->user_id])->find();
       if($total_inte>$userInfo['integral']){
            $msg['message']=checkMsg(INTEGRAL_LESS);
            return $msg;
       }
      $task_data=[
          'uid'  =>$this->user_id,
          'title'=>$title,
          'link' =>$link,
          'total_num'=>$total_num,
          'views_num'=>$total_num,
          'action'   =>$action,
          'inte'   =>$total_inte,
          'add_time'=>time()
      ];
      if($userInfo['type']==1){
          $task_data['type']=1;
      }
      $res=$this->taskModel->insertGetId($task_data);
      if($res){
          $user_inte=$userInfo['integral']-$total_inte;
          $this->userModel->save(['integral'=>$user_inte],['uid'=>$this->user_id]);
          $msg['message']=checkMsg(PUSH_SUCCESS);
      }else{
          $msg['message']=checkMsg(PUSH_FAIL);
      }
      return $msg;
   }
   /**
    *任务详情
    * return json
    */
   public function taskDetail(){
       if(empty($this->userInfo)){
         $msg['message']=checkMsg(LOGIN_ERROR);
         return $msg;
       }
       $tid = $this->request->post('tid');
       if(empty($tid)){
           $msg['message']=checkMsg(CANSHU_ERROR);
           return $msg;
       }
       $info = $this->taskModel->where(['tid'=>$tid])->find();
       if(empty($info)){
           $msg['message']=checkMsg(GET_DATA_FAILE);
           return $msg;
       }elseif($info['status']==0){
           $msg['message']=checkMsg(TASK_IS_UNDO);
           $msg['info']=$info;
           return $msg;
       }else{
           if($info['uid']==$this->user_id){
               $msg['message']=checkMsg(CANNOT_SEE_SELF);
               return $msg;
           }
           $data=[
               'uid' =>$this->user_id,
               'tid' =>$tid
           ];
          $count = $this->task_log->where($data)->count();
          if($count<1){
              $data['addtime']=time();
              $this->task_log->insertGetId($data);
              $info['log_info']=[];
          }else{
              $logInfo=$this->task_log->where($data)->find();
              $info['log_info']=$logInfo;
          }
          $user_name=$this->userModel->where(['uid'=>$this->user_id])->find()['user_name'];
           $info['images']=$this->task_img->where(['tid'=>$tid,'uid'=>$this->user_id])->field('type,img_path')->select();
           $msg['message']=checkMsg(GET_DATA_SUCCESS);
           $msg['data']=$info;
           $msg['user_name']=$user_name;
       }
       return $msg;
   }
 /**
  *记录列表
  * return json
  */
  public function logList(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $type = $this->request->post('type',1); //type:1:我的发布 2:我的观看
      if($type==1){
          $list=$this->taskModel->where(['uid'=>$this->user_id,'status'=>1])->order('tid','desc')->select();
          foreach($list as $key=>$value){
              $list[$key]['confirm_count']=$this->task_log->where(['tid'=>$value['tid'],'status'=>2])->count();
          }
      }else{
          $list=$this->task_log->alias('tl')
                               ->join('dy_task t','t.tid=tl.tid','left')
                               ->where(['tl.uid'=>$this->user_id])
                               ->where('t.views_num','>',0)
                               ->order('tl.addtime','desc')
                               ->field('tl.id,tl.status,tl.reason,tl.addtime,t.tid,t.title,t.total_num,t.views_num,t.action')
                               ->select();
          foreach($list as $key=>$value){
              if($value['status']==1){
                  $time=time()-$value['addtime'];
                  if($time>3600){
                      $this->task_log->save(['status'=>2],['tid'=>$value['tid'],'uid'=>$this->user_id]);
                      $taskInfo = $this->taskModel->where(['tid'=>$value['tid']])->find();
                      $action_arr=explode(',',$taskInfo['action']);
                      $num=count($action_arr);
                      $this->userModel->where(['uid'=>$this->user_id])->setInc('integral',$num);
                      $list[$key]['status']=2;
                  }
              }
          }
      }
      if(!empty($list)){
          $msg['message']=checkMsg(GET_DATA_SUCCESS);
          $msg['data']=$list;
      }else{
          $msg['message']=checkMsg(GET_DATA_FAILE);
      }
      return $msg;
  }
  /**
   *发布的记录详情
   * return json
   */
  public function logDetail(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $tid = $this->request->post('tid');
      if(empty($tid)){
          $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      $info = $this->taskModel->where(['tid'=>$tid,'uid'=>$this->user_id])->field('title,total_num,views_num')->find();
      if(empty($info)){
          $msg['message']=checkMsg(GET_DATA_FAILE);
          return $msg;
      }
      $info['confim_count']=$this->task_log->where(['tid'=>$tid,'status'=>2])->count();
      $look_list =$this->task_log->alias('l')
                                 ->join('dy_user u','u.uid=l.uid','left')
                                 ->where(['l.tid'=>$tid])
                                 ->field('u.uid,u.user_name,l.id as log_id,l.status')
                                 ->select();
      $msg['message']=checkMsg(GET_DATA_SUCCESS);
      $msg['info']=$info;
      $msg['look_list']=$look_list;
      return $msg;
  }
  /**
   *提交任务的详情
   * return json
   */
  public function submitLoginfo(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $log_id = $this->request->post('log_id');
      if(empty($log_id)){
          $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      $info =$this->task_log->where(['id'=>$log_id])->find();
      if(empty($info)){
          $msg['message']=checkMsg(GET_DATA_FAILE);
          return $msg;
      }
      $taskInfo = $this->taskModel->where(['tid'=>$info['tid']])->find();
      $info['task_title']=$taskInfo['title'];
      $info['task_link']=$taskInfo['link'];
      $info['task_action']=$taskInfo['action'];
      $user_info=$this->userModel->where(['uid'=>$info['uid']])->find();
      $info['user_name']=$user_info['user_name'];
      $image_list = $this->task_img->where(['tid'=>$info['tid'],'uid'=>$info['uid']])->field('type,img_path')->select();
      $info['image_list']=$image_list;
      $msg['message']=checkMsg(GET_DATA_SUCCESS);
      $msg['info']=$info;
      return $msg;
  }
  /**
   *撤销任务
   * return json
   */
  public function cancelTask(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $tid = $this->request->post('tid');
      if(empty($tid)){
          $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      $count=$this->taskModel->where(['uid'=>$this->user_id,'tid'=>$tid])->count();
      if($count<1){
          $msg['message']=checkMsg(TASK_NOT_EXIST);
          return $msg;
      }
      $info = $this->taskModel->where(['tid'=>$tid,'uid'=>$this->user_id])->find();
      $res = $this->taskModel->save(['status'=>0],['tid'=>$tid]);
      if($res){
          $action_arr=explode(',',$info['action']);
          $count_log=$this->task_log->where(['tid'=>$tid])->where(['status'=>['<>',2]])->count();
          $count=$info['views_num']+$count_log;
          $integral=count($action_arr)*$count;
          $userInfo=$this->userModel->where(['uid'=>$this->user_id])->find();
          $total_integral = $integral+$userInfo['integral'];
          $this->userModel->save(['integral'=>$total_integral],['uid'=>$this->user_id]);
          $this->task_log->where(['tid'=>$tid])->delete();
          $msg['message']=checkMsg(CANCEL_SUCCESS);
      }else{
          $msg['message']=checkMsg(CANCEL_FAIL);
      }
      return $msg;
  }
  /**
   *用户信息
   * return json
   */
  public function userInfo(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $info = $this->userModel->where(['uid'=>$this->user_id])->find();
      $msg['message']=checkMsg(GET_DATA_SUCCESS);
      $msg['info']=$info;
      return $msg;
  }
  /**
   *上传图片
   * return json
   */
  public function uploadImg(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $checkData=array(
          'size'  =>'15678000',
          'ext'   =>'jpg,png,gif'
      );
      return $this->upload($checkData);
  }
  /**
   *提交任务
   * return json
   */
  public function submitTask(){
      if(empty($this->userInfo)){
          $msg['message']=checkMsg(LOGIN_ERROR);
          return $msg;
      }
      $tid = $this->request->post("tid");
      $images=$this->request->post('images/a');
      if(empty($tid)){
          $msg['message']=checkMsg(CANSHU_ERROR);
          return $msg;
      }
      $info=$this->taskModel->where(['tid'=>$tid])->find();
      $action_arr=explode(',',$info['action']);
      $type_arr=[];
      foreach($images as $v){
          $type_arr[]=$v['type'];
      }
      if(in_array(1,$action_arr) || in_array(2,$action_arr)){
          if(!in_array(1,$type_arr)){
              $msg['message']=checkMsg(CHOSE_FUCE_LIKE_IMG);
              return $msg;
          }
      }

      if(in_array(3,$action_arr)){
          if(!in_array(2,$type_arr)){
              $msg['message']=checkMsg(CHOSE_COMMENT_IMG);
              return $msg;
          }
      }
      if(in_array(4,$action_arr)){
          if(!in_array(3,$type_arr)){
              $msg['message']=checkMsg(CHOSE_COMMENT_IMG);
              return $msg;
          }
      }
      foreach($images as $key=>$value){
          $insert_data=[
              'tid'  =>$tid,
              'uid'  =>$this->user_id,
              'type' =>$value['type'],
              'img_path'=>$value['path'],
              'add_time'=>time()
          ];
          $this->task_img->insertGetId($insert_data);
      }
      $rem_view=($info['views_num']-1);
      $this->taskModel->save(['views_num'=>$rem_view],['tid'=>$tid]);
      $this->task_log->save(['status'=>1],['tid'=>$tid,'uid'=>$this->user_id]);
      $msg['message']=checkMsg(SUBMIT_SUCCESS);
      return $msg;
  }
 /**
  *审核用户的提交
  *return json
  */
 public function auditSubmit(){
     if(empty($this->userInfo)){
         $msg['message']=checkMsg(LOGIN_ERROR);
         return $msg;
     }
     $log_id = $this->request->post('log_id');
     $type = $this->request->post('type'); //1:通过审核 0:拒绝
     $reason = $this->request->post('reason');
     if(empty($log_id)){
         $msg['message']=checkMsg(CANSHU_ERROR);
         return $msg;
     }
     $log_info = $this->task_log->where(['id'=>$log_id])->find();
     $taskInfo = $this->taskModel->where(['tid'=>$log_info['tid']])->find();
     $action_arr=explode(',',$taskInfo['action']);
     $num=count($action_arr);
     if($type){
         $this->task_log->startTrans();
         try{
             $res=$this->task_log->save(['status'=>2,'reason'=>$reason],['id'=>$log_id]);
             $taskInfo = $this->taskModel->where(['tid'=>$log_info['tid']])->find();
             $action_arr=explode(',',$taskInfo['action']);
             $num=count($action_arr);
             $this->userModel->where(['uid'=>$log_info['uid']])->setInc('integral',$num);
             $this->task_log->commit();
             $msg['message']=checkMsg(UPDATE_SUCCESS);
             return $msg;
         }catch (Exception $e){
            $this->task_log->rollback();
            $msg['message']=checkMsg(UPDATE_FAIL);
            return $msg;
         }
     }else{
         if(empty($reason)){
             $msg['message']=checkMsg(REASON_CONNOT_EMPTY);
             return $msg;
         }
         $res=$this->task_log->save(['status'=>3,'reason'=>$reason],['id'=>$log_id]);
         if($res){
             $this->taskModel->where(['tid'=>$taskInfo['tid']])->setInc('views_num',1);
             $msg['message']=checkMsg(UPDATE_SUCCESS);
         }else{
             $msg['message']=checkMsg(UPDATE_FAIL);
         }
         return $msg;
     }
 }
 /**
  *分享/转发
  *return json
  */
 public function shareUser(){
     if(empty($this->userInfo)){
         $msg['message']=checkMsg(LOGIN_ERROR);
         return $msg;
     }
     $msg['message']=checkMsg(GET_DATA_SUCCESS);
     $msg['user_id']=$this->user_id;
     return $msg;
 }
 /**
  *编辑资料
  * return json
  */
 public function editUser(){
     if(empty($this->userInfo)){
         $msg['message']=checkMsg(LOGIN_ERROR);
         return $msg;
     }
     $user_name = $this->request->post('user_name');
     $phone = $this->request->post('phone');
     if(empty($user_name) || empty($phone)){
         $msg['message']=checkMsg(CANSHU_ERROR);
         return $msg;
     }
     $res=$this->userModel->save(['user_name'=>$user_name,'phone'=>$phone],['uid'=>$this->user_id]);
     if($res){
         $msg['message']=checkMsg(UPDATE_SUCCESS);
     }else{
         $msg['message']=checkMsg(UPDATE_FAIL);
     }
     return $msg;
 }
 /**
  *邀请记录
  * return json
  */
 public function invitLog(){
     if(empty($this->userInfo)){
         $msg['message']=checkMsg(LOGIN_ERROR);
         return $msg;
     }
     $list=$this->userModel->where(['invited_id'=>$this->user_id])->order('uid','desc')->select();
     foreach ($list as $key=>$value){
         $list[$key]['add_time']=date("Y-m-d H:i:s",$value['add_time']);
     }
     if(!empty($list)){
         $msg['message']=checkMsg(GET_DATA_SUCCESS);
         $msg['list']=$list;
     }else{
         $msg['message']=checkMsg(GET_DATA_FAILE);
     }
     return $msg;
 }
}
